package com.cloud.newRibbonImpl;


import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
/**
 * 自定义ribbon实现，也可以实现Irule接口，
 * 在Ribbon中写入实现方法由ribbon自行管理
 * NewRibbon implements IRule
 */
public class NewRibbon {
    AtomicInteger atomicInteger = new AtomicInteger(0);

    public final Integer CAS() {
        Integer now = 0;
        Integer next = 0;
        {
            do {
                now = atomicInteger.get();
                next = now >= Integer.MAX_VALUE ? 0 : now + 1;
            } while (!atomicInteger.compareAndSet(now, next));//原子操作进行递增，高并发下进行cas操作选取对应服务
        }
        return next;
    }

    public ServiceInstance serviceInstance(List<ServiceInstance> list) {
        ServiceInstance instance = null;
        Integer next = CAS();
        Integer instanceSize = list.size();
        instance = list.get(next % instanceSize);
        return instance;
    }
}
